import React, { Component, useRef, useEffect, useState } from "react";
import { Drawer, Button, message, Select, Input, Space, Affix, Table, Popover, Form, DatePicker } from 'antd';
import { ArrowLeftOutlined} from '@ant-design/icons';
import {
    CmdbContent,
    HcpTableFilterBar,
    CmdbHeader ,
    TableColumsProperties,
    TempImportModal,
    HcpTableTooltip,
    useModelList
} from "@/components";
import moment from 'moment';
import cmdbres from "@/data/cmdbres";
import request, { exportFile } from "@/utils/request";
import hcpUtils from "@/utils/hcpUtils";
import RelationBizSelect from "@/modules/resource/resourceCatalog/ecsInstance/relationBizSelect";

const { RangePicker } = DatePicker;
const BusinessEcsInstance = ({ history, match, location, treeNode, cmModuleId, tabVisible }) => {
    const [form] = Form.useForm();
    const [properties, setProperties] = useState({});
    const [loading, setLoading] = useState(false);
    const [placement, setPlacement] = useState('right');
    const [tableData, setTableData] = useState([]);
    const [row, setRow] = useState({});
    const [tableHeaderFields, setTableHeaderFields] = useState([]);
    const [checkedFields, setCheckedFields] = useState([]);
    const [unCheckedFields, setUnCheckedFields] = useState([]);
    const [defaultCheckedFields, setDefaultCheckedFields] = useState([]);
    const [defaultUnCheckedFields, setDefaultUnCheckedFields] = useState([]);
    const [visible, setVisible] = useState(false);
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const [query_key, setQuery_key] = useState("");  //命名采用下划线方式方便直接传值
    const [query_keyType, setQuery_keyType] = useState("");
    const [inputHolderMess, setInputHolderMess] = useState("");
    const [fieldsEnum , setFieldsEnum] =  useState([]);
    const state =  location?.state;
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0,
    });
    const [module] = useModelList("server");

    const getTableData = async (params = { current: 1, pageSize: 10 }) => {
        if(!treeNode) {
            message.warning("请先选择拓扑实例！");
            return;
        }
        const {moduleCode, key, title } = treeNode;
        let topoParam = null;
        const attr = moduleCode ? moduleCode : title;

        switch(attr) {
            case "biz": topoParam = {bizId: key};break;
            case "set":case "空闲机池": topoParam = {setId: key};break;
            case "service":case "空闲机":case "故障机":case "待回收": topoParam = {serviceId: key};break;
            default: topoParam = {mainLineInstanceId: key};
        }
        setSelectedRowKeys([]);
        setLoading(true);
        try {
            const res = await request({
                ...cmdbres.queryBizServers,
                data: {
                    pageSize: params.pageSize,
                    pageNumber: params.current,
                    ...topoParam,
                    ...properties,
                    cmModuleId: [cmModuleId],
                    sort:{
                        cm_create_time:"DESC"
                    },
                },
            });
            setLoading(false);
            if (res && res.data) {
                setPagination((pagination) => ({
                    ...pagination,
                    current: res.pageNumber,
                    pageSize: res.pageSize,
                    total: res.total,
                }));
                res.data.map((item, index) => {
                    item.key = item.cm_id;
                    enumTranslate(item)
                });
                setTableData(res.data);
            } else {
                setTableData([]);
            }
        } catch (error) {
            console.log(error);
        }
    };

    const onFinish = () => {
        setRow({});
        let query_value = form.getFieldValue([query_key]);
        if(query_keyType == 'date') {
            setProperties({
                queryFilter: {
                    GTE: {// 大于等于号（>=）
                        [query_key]: query_value?.[0] ? query_value[0].format('YYYY-MM-DD') : undefined
                    },
                    LTE: {// 小于等于号(<=)
                        [query_key]: query_value?.[1] ? query_value[1].format('YYYY-MM-DD') : undefined
                    }
                }
            })
        } else if(query_keyType == 'datetime') {
            if(!(query_value && query_value.length)) {
                setProperties({});
                return;
            }
            setProperties({
                timeConditions:[{
                    field: query_key,
                    start: query_value[0].format('YYYY-MM-DD HH:mm:ss'),
                    end: query_value[1].format('YYYY-MM-DD HH:mm:ss')
                }]

            })
        } else {
            setProperties({
                queryFilter: { LIKE: { [query_key]: query_value } }
            })
        }
    };

    useEffect(() => {
        if(properties && tableHeaderFields.length>0) {
            getTableData();
        }
    }, [properties, tableHeaderFields, treeNode]);

    const enumTranslate = (data) => {
        for(let fieldKey in data) {
            if(fieldsEnum[fieldKey]) {
                let enumValue = fieldsEnum[fieldKey];
                const translateState =  enumValue[data[fieldKey]];
                if(translateState) {
                    data[fieldKey] = enumValue[data[fieldKey]];
                }
            }
        }
    }

    const queryTableHeaders = async () => {
        setLoading(true);
        try {
            const res = await request({
                ...cmdbres.queryTableHeader,
                params: {
                    cm_module_id: module.cmModuleId,
                },
            });
            setLoading(false);
            if (res && res.code == 200) {
                const fieldData = res.data;
                const checkedArrs = [];
                const unCheckedArrs = [];
                let enumValues = {};
                fieldData.fields.map((item, index) => {
                    let field = {
                        ...item,
                        key: item.propertyKey,
                        title: item.unit ? `${item.propertyName}(${item.unit})` : item.propertyName,
                        dataIndex: item.propertyKey,
                        width: 130,
                        copyable: true,
                        ellipsis: true,
                    };
                    if(['date', 'datetime'].includes(item.propertyType)) {
                        const formString = item.propertyType == 'date' ? 'YYYY-MM-DD': 'YYYY-MM-DD HH:mm:ss';
                        field.render =  (text, record) => hcpUtils.timeConversion(text, formString)
                    }

                    if(item.propertyType == "enum" && field.woIsHidden === 0) {
                        let enumValueStr =item.propertyEnumValue.replace(/'/g,"\"");
                        enumValues[field.key] = JSON.parse(enumValueStr);
                    }
                    setFieldsEnum(enumValues);

                    if (field.woIsHidden === 0) {
                        checkedArrs.push(field);
                    } else {
                        unCheckedArrs.push(field);
                    }
                });


                const noOperCheckedArrs = [...checkedArrs];

                setTableHeaderFields([{
                    key: 'cm_unid',
                    title: 'ID',
                    dataIndex: 'cm_unid',
                    width: 130,
                    copyable: true,
                    ellipsis: true,
                    render: (text, record) => (
                        <HcpTableTooltip
                            label="ID"
                            showValue={record.cm_unid}
                            copyValue={record.cm_unid}
                            onClick={() => {
                                history.push({
                                    pathname: "/resource/catalog/detail/" + module.cmModuleId,
                                    state: {info:record, moduleData: module, goBackUrl: "/business/topology"}
                                });
                            }}
                        />
                    )},...checkedArrs
                ])
                setCheckedFields(noOperCheckedArrs);
                setDefaultCheckedFields([...noOperCheckedArrs])
                setUnCheckedFields(unCheckedArrs);
                setDefaultUnCheckedFields([...unCheckedArrs]);
            } else {
                setCheckedFields([]);
                setUnCheckedFields([]);
            }
        } catch (error) {
            console.log("getTableData -> error", error);
        }
    }

    const queryUncheckedField = async (value) => {
        try {
            const res = await request({
                ...cmdbres.queryTableHeader,
                params: {
                    cm_module_id: module?.cmModuleId,
                    property_name: value
                },
            });
            if (res && res.code == 200) {
                const fieldData = res.data;
                const unCheckedArrs = [];
                fieldData.fields.map((item, index) => {
                    let field = {
                        ...item,
                        key: index,
                        title: item.propertyName,
                        dataIndex: item.propertyKey,
                        width: 130,
                        copyable: true,
                        ellipsis: true,
                    };
                    if (field.woIsHidden === 1) {
                        unCheckedArrs.push(field);
                    }
                });
                setUnCheckedFields(unCheckedArrs);
            } else {
                setUnCheckedFields([]);
            }
        } catch (error) {
            console.log("getTableData -> error", error);
        }
    }

    useEffect(() => {
        if(tabVisible && module && module.cmModuleId) {
            queryTableHeaders();
        }
    }, [module, tabVisible]);


    const setSelectProperty = (field) => {
        setQuery_key(field?.propertyKey);
        setQuery_keyType(field?.propertyType);
        setInputHolderMess("请输入" + (field?.propertyName || ""));
    }

    useEffect(() => {
        if(!query_key && checkedFields.length>0) {
            setSelectProperty(checkedFields[0]);
        }
    }, [query_key]);

    useEffect(() => {
        if (checkedFields.length > 0 && checkedFields[0].propertyKey != query_key) {
            setSelectProperty(checkedFields[0]);
        }
    }, [checkedFields]);

    const resetScreen = () => {
        form.resetFields();
        if (checkedFields.length > 0) {
            const field = checkedFields[0];
            form.setFieldsValue({
                "query_key": field?.propertyKey
            })
            setSelectProperty(field);
        }
    };

    const onSelectChange = (propertyKey) => {
        const checkSelect = checkedFields.find(function(val){
            return val.propertyKey == propertyKey;
        });
        setSelectProperty(checkSelect);
    }

    const handleTableChange = (e) => {
        getTableData(e);
    };

    const [isBath, setIsBath] = useState(false);
    const rowSelection = {
        selectedRowKeys: selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
            if(selectedRowKeys.length > 0) {
                setIsBath(true);
            }else {
                setIsBath(false);
            }
            setSelectedRowKeys(selectedRowKeys);
        },
    };

    const updateFields = () => {
        setVisible(true)
    }
    /**设置表格列组件里面的方法----------开始 */
    const onClose = () => {
        setVisible(false);
        onReset();
    }

    const onReset = () => {
        setCheckedFields(defaultCheckedFields);
        setUnCheckedFields(defaultUnCheckedFields);
    }

    const onOk = async () =>  {
        setLoading(true);
        let showFields = []
        for(let item of checkedFields) {
            showFields.push(item.propertyKey)
        }
		let param =  {
			namespace: "default",  //先传默认
            cm_module_id: module?.cmModuleId,
            show_fields: showFields
		}

        const res = await request({
			...cmdbres.updateFieldshow,
			data: param
		});
		setLoading(false);
		if (res && res.code == 200) {
			setVisible(false);
			message.success( "修改成功！");
            queryTableHeaders();
		} else {
			if(res) message.error(res.msg);
		}

    }

    const updateUncheckedFields = (item) => {
        const newUnCheckedFields = unCheckedFields.filter(function(val){
            return val.propertyKey != item.propertyKey;
        });
        var newCheckedFields = checkedFields;
        newCheckedFields.push(item);
        setCheckedFields(newCheckedFields);
        setUnCheckedFields(newUnCheckedFields);
    }

    const updateCheckedFields = (item) => {
        const newFields = checkedFields.filter(function(val){
            return val.propertyKey != item.propertyKey;
        });
        var newUnCheckedFields = unCheckedFields;
        newUnCheckedFields.push(item);
        setCheckedFields(newFields);
        setUnCheckedFields(newUnCheckedFields);
    }
    /**设置表格列组件里面的方法----------结束 */

    return (
        <>
            <div className="resource-catalog-pane" style={{backgroundColor: "#fff", padding: "0 10px"}}>
                <div className="session-bar">
                    <section style={{width: "20%", float: "left", padding: "5px 10px 15px 0"}}>
                        <Space>
                            <RelationBizSelect
                                assign={false}
                                rowKeys={ isBath ? selectedRowKeys : row && row.cm_unid ? [row.cm_unid] : []}
                                getTableData={getTableData}
                                cmModuleId={cmModuleId}
                            />
                            <Button type="primary" onClick={() => {getTableData()}} >
                                刷新
                            </Button>
                        </Space>
                    </section>
                    <section className="hcp__search__collapse hcp_search_bar" style={{width: "80%", textAlign: "right",  paddingTop: "5px"}}>
                        <section className="hcp__form">
                            <HcpTableFilterBar
                                form={form}
                                resetClick={resetScreen}
                                onSearch={onFinish}
                                updateFields={updateFields}
                                items={[
                                    {
                                    field: { query_key },
                                    component: (
                                        <Input.Group compact style={{ display: "flex"}}>
                                        <Form.Item name="query_key" noStyle>
                                            {
                                                query_key ?
                                                <Select
                                                    style={{ minWidth: '110px', textAlign: "left" }}
                                                    defaultValue={query_key}
                                                    onChange={onSelectChange}
                                                    getPopupContainer={triggerNode => triggerNode.parentElement}
                                                >
                                                    {tableHeaderFields && tableHeaderFields.length > 0 ? checkedFields.map((item, index) => {
                                                        return (
                                                            <Select.Option value={item.propertyKey} defaultValue={checkedFields[0].propertyKey} key={index}>{item.propertyName}</Select.Option>
                                                        )
                                                    }): null}
                                                </Select> : null
                                            }

                                        </Form.Item>
                                        {tableHeaderFields && tableHeaderFields.length > 0 ? tableHeaderFields.map((item, index) => {
                                            return (
                                                <div key={index}>
                                                    {query_key == item.propertyKey ? (
                                                        item.propertyType == 'date' ?
                                                        <Form.Item
                                                            key={item.propertyKey}
                                                            style={{ width: '190px', marginRight:'20px' }}
                                                            name={item.propertyKey}
                                                        >
                                                            <RangePicker format="YYYY-MM-DD"/>
                                                        </Form.Item>
                                                        :
                                                        item.propertyType == 'datetime' ?
                                                        <Form.Item
                                                            key={item.propertyKey}
                                                            style={{ width: '190px', marginRight:'20px'}}
                                                            name={item.propertyKey}
                                                        >
                                                            <RangePicker showTime format="YYYY-MM-DD HH:mm:ss"/>
                                                        </Form.Item>
                                                        :
                                                        <Form.Item
                                                            key={item.propertyKey}
                                                            style={{ width: '190px',marginRight:'20px' }}
                                                            name={item.propertyKey}
                                                        >
                                                            <Input allowClear maxLength={50} placeholder={inputHolderMess} />
                                                        </Form.Item>
                                                    ) : null}
                                                </div>
                                            )
                                        }): null}
                                        </Input.Group>
                                    )
                                    }
                                ]}
                            />
                        </section>
                    </section>
                </div>
                <Table
                    rowKey={record => record.cm_unid}
                    rowSelection={{ ...rowSelection}}
                    columns={tableHeaderFields}
                    loading={loading}
                    dataSource={tableData}
                    scroll={{ x: '100%' }}
                    pagination={{
                        showSizeChanger: true,
                        showQuickJumper: {
                            goButton: (
                                <Button style={{ margin: "0 10px" }}>确定</Button>
                            ),
                        },
                        ...pagination,
                    }}
                    onChange={handleTableChange}
                    hideSetting
                />
            </div>
            {checkedFields.length > 0  ?
            <TableColumsProperties
                placement={placement}
                drawerWidth={600}
                checkedFields={checkedFields}
                setCheckedFields={setCheckedFields}
                unCheckedFields={unCheckedFields}
                setUnCheckedFields={setUnCheckedFields}
                onOk={onOk}
                onClose={onClose}
                onSearch={queryUncheckedField}
                onUpdateCheckedFields={updateCheckedFields}
                onUpdateUncheckedFields={updateUncheckedFields}
                onReset={onReset}
                visible={visible}
            />: null}
        </>
    );
};

export default BusinessEcsInstance;
